import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ImageBackground,
    Animated,
    FlatList,
    RefreshControl,
    ActivityIndicator,
    Dimensions, ScrollView
} from 'react-native';
import {Stack, useRouter} from "expo-router";
import {useEffect, useRef, useState} from "react";
import profileBgImg from "@/assets/images/profileImg/profileImg.png";
import profileChatIcon from "@/assets/images/profileImg/profileChatIcon.png"
import {SceneMap, TabView} from "react-native-tab-view";
import * as React from "react";
import tabBg from "@/assets/images/homeImg/tabBg.png";
import {scaleSize} from "@/utils/screenSize";
import {GestureHandlerRootView} from "react-native-gesture-handler";
import empty_icon from "@/assets/images/concern/empty_fan.png";
import activityTag from "@/assets/images/collection/activityTag.png";
import dateTimeIcon from "@/assets/images/collection/dateTime.png";
import addressIcon from "@/assets/images/collection/address.png";
import Svg, { Line } from 'react-native-svg';
import profileTag_active from "@/assets/images/profileImg/profileTag_active.png"
import profileTag_unactive from "@/assets/images/profileImg/profileTag_unactive.png"
import {useSafeAreaInsets} from "react-native-safe-area-context";
import AntDesign from "@expo/vector-icons/AntDesign";

export default function profileScreen() {

    const router = useRouter();
    const [index, setIndex] = useState(0);
    const animatedValue1 = useRef(new Animated.Value(14)).current;
    const animatedValue2 = useRef(new Animated.Value(14)).current;
    const animatedValue3 = useRef(new Animated.Value(14)).current;

    const itemWidth = 120;
    const underlineWidth = 26;
    const underlineOffset = useRef(new Animated.Value((itemWidth * index) + (itemWidth - 18) / 2)).current;  // 下划线偏移的动画值

    const insets = useSafeAreaInsets();


    const handleTabPress = (index) => {

        Animated.timing(animatedValue1, {
            toValue: index === 0 ? 16 : 14,
            duration: 200,
            useNativeDriver: false,
        }).start();

        Animated.timing(animatedValue2, {
            toValue: index === 1 ? 16 : 14,
            duration: 200,
            useNativeDriver: false,
        }).start();

        Animated.timing(animatedValue3, {
            toValue: index === 2 ? 16 : 14,
            duration: 200,
            useNativeDriver: false,
        }).start();

        setIndex(index);

        // 计算偏移量，确保下划线居中
        const offset = (itemWidth * index) + (itemWidth - underlineWidth) / 2;

        Animated.spring(underlineOffset, {
            toValue: offset,  // 偏移量
            useNativeDriver: true,
        }).start();
    };

    const FristRoute = () => {

        const [data, setData] = useState([]);
        const [loading, setLoading] = useState(false);
        const [refreshing, setRefreshing] = useState(false);
        const [triggerRefresh, setTriggerRefresh] = useState(false);
        const [page, setPage] = useState(1);
        const [refreshingText, setRefreshingText] = useState('下拉刷新');
        const scrollY = new Animated.Value(0); // 用于跟踪滚动偏移

        const router = useRouter();

        // 自定义加载图标组件
        const RefreshControlHeader = ({ refreshing, text }) => (
            refreshing &&  <View style={styles.refreshHeader}>
                {/*{refreshing && <Image source={require('./path/to/your/loading-icon.gif')} style={styles.refreshIcon} />} /!* 替换为你的加载图标 *!/*/}
                <Text style={styles.refreshText}>{text}</Text>
            </View>
        );

        // 初次加载数据
        useEffect(() => {
            loadMoreData();
        }, []);

        useEffect(() => {
            if (triggerRefresh) {
                handleRefresh();
                setTriggerRefresh(false); // Reset trigger
            }
        }, [triggerRefresh]);

        const loadMoreData = () => {
            if (loading) return;

            setLoading(true);
            // 模拟网络请求来获取更多数据
            setTimeout(() => {
                const newData = Array.from({ length: 10 }, (_, index) => `Item ${page * 10 + index + 1}`);
                setData((prevData) => [...prevData, ...newData]);
                setPage((prevPage) => prevPage + 1);
                setLoading(false);
            }, 100);
        };

        const handleRefresh = () => {
            setRefreshing(true);
            setRefreshingText('正在刷新...');
            setPage(1);

            // 模拟网络请求来获取新数据
            setTimeout(() => {
                const newData = Array.from({ length: 10 }, (_, index) => `Item ${index + 1}`);
                setData(newData);
                setRefreshing(false);
                setRefreshingText('下拉刷新');
            }, 100);
        };

        const renderFooter = () => {
            if (!loading) return null;
            if (data.length <= 0) return null;
            return (
                <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                    <ActivityIndicator size="small" />
                    <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
                </View>
            );
        };

        const handleScroll = Animated.event(
            [{ nativeEvent: { contentOffset: { y: scrollY } } }],
            {
                useNativeDriver: false,
                listener: event => {
                    const offsetY = event.nativeEvent.contentOffset.y;

                    if (!refreshing) {
                        // 根据下拉距离更新文本
                        if (offsetY < -100) {
                            setRefreshingText('松开刷新'); // 超过 -100 的偏移量显示松开刷新
                        } else if (offsetY < 0) {
                            setRefreshingText('下拉刷新'); // 在 -100 到 0 之间时显示下拉刷新
                        }
                    }
                },
            }
        );

        const onScrollEnd = () => {
            scrollY.addListener(({ value }) => {
                if (!refreshing && value < -100) {
                    setTriggerRefresh(true); // 触发刷新
                }
            });
        };

        const ActivityItem = () => {
            return (
                <View style={styles.activityContainer}>
                    <View style={styles.activitybody}>
                        <View style={styles.activityBanner}>
                            <Image source={empty_icon} style={{ width: "100%", height: "100%" }} />
                            {
                               true && (
                                    <ImageBackground source={profileTag_active} style={styles.activityTagWarp}>
                                        <Text style={styles.tagText}>进行中</Text>
                                    </ImageBackground>
                                )
                            }

                            {
                                false && (
                                    <ImageBackground source={profileTag_active} style={styles.activityTagWarp}>
                                        <Text style={styles.tagText}>待开始</Text>
                                    </ImageBackground>
                                )
                            }

                            {
                               false && (
                                    <ImageBackground source={profileTag_unactive} style={styles.activityTagWarp}>
                                        <Text style={styles.tagText}>已结束</Text>
                                    </ImageBackground>
                                )
                            }

                            {
                                false && (
                                    <ImageBackground source={profileTag_unactive} style={styles.activityTagWarp}>
                                        <Text style={styles.tagText}>已取消</Text>
                                    </ImageBackground>
                                )
                            }

                        </View>
                        <View style={styles.activityContent}>
                            <View style={styles.activityTitleWarp}>
                                <Text
                                    style={styles.activityTitle}
                                    numberOfLines={2}
                                    ellipsizeMode="tail"
                                >周末去露营去嗨p末去</Text>
                            </View>
                            <View style={styles.activityTag}>
                                <Text style={styles.activityTagText}>交友</Text>
                            </View>
                            <View style={styles.activityDateWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={dateTimeIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={ styles.activityDate }>10.15 18:00-22:00</Text>
                            </View>
                            <View style={styles.activityAdressWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={addressIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={styles.activityAdress}>广州市琶洲暴力世贸101</Text>
                            </View>
                        </View>
                    </View>
                    <View style={{ paddingHorizontal: 12, paddingBottom: 10, }}>
                        <Svg height="2" width="100%">
                            <Line
                                x1="0"
                                y1="0"
                                x2={Dimensions.get('window').width} // 使用屏幕宽度
                                y2="0"
                                stroke="#E4E6EC"
                                strokeWidth="2"
                                strokeDasharray="5, 5" // 设置虚线的线段和间距
                            />
                        </Svg>
                    </View>
                    <View style={styles.activityFooter}>
                        <View style={styles.joinList}>
                            <View style={styles.joinListWarp}>
                                <View style={styles.joinAvator}>

                                </View>
                                <View style={[styles.joinAvator,styles.maLeft]}>
                                </View>
                                <View style={[styles.joinAvator,styles.maLeft]}>
                                </View>
                                <View style={[styles.joinAvator,styles.maLeft]}>
                                </View>
                            </View>
                            <View style={styles.joinContent}>
                                <Text style={styles.joinContentText}>正在招募...</Text>
                            </View>
                        </View>
                        <View style={styles.activityMoney}>
                            <Text style={styles.activityMoneyText}>¥30</Text>
                        </View>
                    </View>
                </View>
            )
        };

        return (
            <View style={{ paddingTop:  10, borderTopWidth: 0.5, borderColor: "#E4E6EC" }}>
                <FlatList
                    data={data}
                    renderItem={({ item }) => <ActivityItem/>}
                    keyExtractor={(item, index) => index.toString()}
                    onEndReached={loadMoreData}
                    onEndReachedThreshold={0.5} // 当滚动到距离底部还有50%的时候触发
                    ListFooterComponent={renderFooter}
                    refreshControl={
                        <RefreshControl
                            refreshing={refreshing}
                            // onRefresh={handleRefresh} // 绑定刷新函数
                            title={refreshing ? '' : refreshingText} // 在正在刷新状态时不显示文本
                            titleColor="#333" // 设置提示文字颜色
                            tintColor="transparent" // 隐藏刷新指示器
                        />
                    }
                    onScroll={handleScroll}
                    onScrollEndDrag={onScrollEnd}
                    ListHeaderComponent={<RefreshControlHeader refreshing={refreshing} text={refreshingText} />}
                />
            </View>
        )
    };

    const TwoRoute = () => {
        return (
            <View>
                <Text>two</Text>
            </View>
        )
    };

    const [routes] = React.useState([
        { key: 'first', title: 'Tab 1' },
        { key: 'second', title: 'Tab 2' },
    ]);


    const renderScene = SceneMap({
        first: FristRoute,
        second: FristRoute,
    });

    const goOtherFans = function () {
        router.push("/profile/otherFans");
    };

    const goOtherGroup = function () {
        router.push("/profile/otherGroup")
    };

    const back = function () {
        router.back();
    };


    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7", position: "relative" }}>
            <Stack.Screen
                options={{headerShown: false}}
            />
            <View>
                <ImageBackground source={profileBgImg} style={styles.profileContainer}>
                    <TouchableOpacity onPress={back}>
                        <View style={[styles.headersIcon, { paddingTop: insets.top }]}>
                            <AntDesign name="left" size={21} color="#FFF"/>
                        </View>
                    </TouchableOpacity>

                   <View style={{ marginTop: 20 }}>
                       <View style={{ flexDirection: "row", alignItems: "center" }}>
                           <View style={styles.avatorImg}>

                           </View>
                           <View style={styles.nicknameWrap}>
                               <View>
                                   <Text style={styles.nickname}>烫金困</Text>
                               </View>
                               <View style={styles.userIDWrap}>
                                   <Text style={styles.userID}>UID:232435542</Text>
                               </View>
                           </View>
                       </View>
                       <View style={styles.desc}>
                           <Text style={styles.descText} numberOfLines={2}>
                               简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介
                           </Text>
                       </View>
                       <View style={styles.followContainer}>
                           <View style={styles.followNumWrap}>
                               <TouchableOpacity onPress={goOtherFans}>
                                   <View>
                                       <View>
                                           <Text style={[styles.followWhite]}>1232</Text>
                                       </View>
                                       <View>
                                           <Text style={[styles.followWhite]}>关注</Text>
                                       </View>
                                   </View>
                               </TouchableOpacity>
                               <TouchableOpacity onPress={goOtherFans}>
                                   <View>
                                       <View>
                                           <Text style={[styles.followWhite]}>1232</Text>
                                       </View>
                                       <View>
                                           <Text style={[styles.followWhite]}>粉丝</Text>
                                       </View>

                                   </View>
                               </TouchableOpacity>
                               <TouchableOpacity onPress={goOtherGroup}>
                                   <View>
                                       <View>
                                           <Text style={[styles.followWhite]}>1232</Text>
                                       </View>
                                       <View>
                                           <Text style={[styles.followWhite]}>社群</Text>
                                       </View>
                                   </View>
                               </TouchableOpacity>
                           </View>
                           {
                               false && (
                                   <TouchableOpacity>
                                       <View style={styles.follow}>
                                           <Text style={styles.followText}>关注</Text>
                                       </View>
                                   </TouchableOpacity>
                               )
                           }

                           {
                               true && (
                                   <TouchableOpacity>
                                       <View style={styles.followActive}>
                                           <Text style={styles.followActiveText}>已关注</Text>
                                       </View>
                                   </TouchableOpacity>
                               )
                           }

                           <TouchableOpacity>
                               <View style={styles.chatRoute}>
                                   <Image source={profileChatIcon} style={{ width: "100%", height: "100%"}}/>
                               </View>
                           </TouchableOpacity>
                       </View>
                   </View>
                </ImageBackground>
            </View>
            <View style={styles.followContent}>
                <View style={styles.profileHeader}>
                    <View style={styles.headerTab}>
                        <View style={{ width: 240, flexDirection: "row", position: "relative" }}>
                            <TouchableOpacity onPress={() => handleTabPress(0)}>
                                <View style={[styles.headerTabItem]}>
                                    <Animated.Text style={
                                        [
                                            styles.headerTabItemText,
                                            {
                                                fontWeight: index === 0 ? 'bold' : 400,
                                                color: index == 0 ? "#EC6138" : "#2A2B30",
                                            }
                                        ]}
                                    >
                                        参加的活动
                                    </Animated.Text>

                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => handleTabPress(1)}>
                                <View style={[styles.headerTabItem]}>
                                    <Animated.Text style={
                                        [
                                            styles.headerTabItemText,
                                            {
                                                fontWeight: index === 1 ? 'bold' : 400,
                                                color: index == 1 ? "#EC6138" : "#2A2B30",
                                            }
                                        ]}>
                                        创建的活动
                                    </Animated.Text>
                                </View>
                            </TouchableOpacity>
                            <Animated.View
                                style={[
                                    styles.underline,
                                    {
                                        width: underlineWidth,
                                        transform: [{ translateX: underlineOffset }],
                                    },
                                ]}
                            />
                        </View>
                    </View>
                </View>
                <View style={{ flex: 1 }}>
                    <GestureHandlerRootView style={{ flex: 1 }}>
                        <TabView
                            navigationState={{ index, routes }}
                            renderScene={renderScene}
                            onIndexChange={handleTabPress}
                            renderTabBar={() => null}
                        />
                    </GestureHandlerRootView>
                </View>
            </View>
        </View>

    );
}

const styles = StyleSheet.create({
    profileContainer: {
        paddingHorizontal: 12,
        paddingBottom: 30,
        backgroundColor: "#000"
    },
    profileHeadersWrap: {
        flexDirection: "row",
        alignItems: "center",
    },
    avatorImg: {
        width: 60,
        height: 60,
        backgroundColor: "red",
        borderWidth: 1,
        borderColor: "#fff",
        borderRadius: 50,
    },
    nicknameWrap: {
        marginLeft: 10,
    },
    nickname: {
        fontSize: 22,
        color: "#FFF",
    },
    userIDWrap: {
        marginTop: 2,
    },
    userID: {
        color: "#fff",
        fontSize: 12,
    },
    desc: {
        marginTop: 14,
    },
    descText: {
        color: "#FFF",
        fontSize: 12,
    },
    followContainer: {
        flexDirection: "row",
        marginTop: 14,
    },
    followNumWrap: {
        flexDirection: "row",
        justifyContent: "space-between",
        flex: 1,
    },
    followText: {
        fontSize: 12,
        color: "#FFF",
    },
    follow: {
        width: 80,
        height: 24,
        borderRadius: 17,
        backgroundColor: "#EC6138",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginLeft: 74
    },
    followActiveText: {
        fontSize: 12,
        color: "#FFF",
    },
    followActive: {
        width: 80,
        height: 24,
        borderRadius: 17,
        backgroundColor: "rgba(255,255,255,0.3)",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginLeft: 74
    },

    chatRoute: {
        width: 40,
        height: 24,
        marginLeft: 12,
    },
    followWhite: {
        color: "#fff",
        fontSize: 12,
        textAlign: "center",
    },
    followContent: {
        flex: 1,
        marginTop: -10,
        backgroundColor: "#F7F7F7",
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10,
    },
    headerTab: {
        flexDirection: "row",
        justifyContent: "center",
        position: "relative",
        paddingLeft: scaleSize(25),

        // width: scaleSize(300),
        // paddingLeft: 25,
    },
    headerTabItem: {
        width: 120,
        height: 20,
        // backgroundColor: "red",
    },
    headerTabItemText: {
        textAlign: "center",
        fontSize: 14,
    },
    scene: {
        flex: 1,
        // justifyContent: 'center',
        // alignItems: 'center',
    },
    tabBar: {
        flexDirection: 'row',
        backgroundColor: 'white',
        position: 'relative', // 需要相对定位来放置指示器
        width:scaleSize(350),
        margin: "auto",
    },
    tabItem: {
        flex: 1,
        alignItems: 'center',
        paddingTop: 10,
        paddingBottom: 9,
        fontSize: 14,
        color: "#2A2B30",
    },
    indicator: {
        position: 'absolute',
        height: 3,
        backgroundColor: '#EC6138',
        bottom: 0,
        borderRadius: 5,
    },
    tabHeader: {
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderBottomColor: "#F1F2F5",
        marginBottom: 12,
    },
    activeTab: {
        borderBottomWidth: 2,
        borderBottomColor: '#000',
    },
    searchIcon: {
        width: 17,
        height: 17,
    },
    underline: {
        height: 2,
        backgroundColor: '#EC6138',
        position: 'absolute',
        bottom: -5,
        left: 0,
        borderRadius: 30,
    },
    profileHeader: {
        paddingTop: 20,
        // borderWidth: 0.5,
        borderBottomColor: "#E4E6EC",
        paddingBottom: 6,
    },
    activityContainer: {
        // flexDirection: "row",
        marginLeft: 12,
        marginRight: 12,
        // height: scaleSize(164),
        backgroundColor: "#fff",
        borderRadius: 8,
        marginBottom: 12,
    },
    activitybody: {
        padding: 12,
        flexDirection: "row",

    },
    activityBanner: {
        position: "relative",
        width: scaleSize(110),
        height: scaleSize(110),
        backgroundColor: "blue",
        borderRadius: 4,
    },
    activityContent: {
        marginLeft: 10,
    },
    activityTitleWarp: {
        width: scaleSize(192),
    },
    activityTitle: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#2A2B30",
        letterSpacing: 1.2,
        lineHeight: 22,
    },
    addressIcon: {
        width: scaleSize(11),
        height: scaleSize(11),
    },
    activityTag: {
        width: scaleSize(28),
        height: scaleSize(12),
        backgroundColor: "rgba(255,70,0,0.1)",
        borderRadius: 10,
        marginTop: 6,
    },
    activityTagText: {
        fontSize: 8,
        color: "#EC6138",
        textAlign: "center",
        lineHeight: 12,
    },
    activityDateWarp: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 6,
        marginBottom: 6,
    },
    activityDate: {
        marginLeft: 3,
        fontSize: 12,
        color: "#676978"
    },
    activityAdressWarp: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityAdress: {
        fontSize: 12,
        color: "#676978",
        marginLeft: 3,
    },
    joinList: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityFooter: {
        flexDirection: "row",
        paddingLeft: 12,
        paddingRight: 12,
        paddingBottom: 10,
        justifyContent: "space-between",
        alignItems: "center",
    },
    joinAvator: {
        width: scaleSize(20),
        height: scaleSize(20),
        backgroundColor: "red",
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 1,
    },
    maLeft: {
        marginLeft: -7,
    },
    joinListWarp: {
        flexDirection: "row",
    },
    joinContent: {
        marginLeft: 10,
    },
    joinContentText: {
        color: "#333",
        fontSize: 12,
        fontWeight: "bold"
    },
    activityMoney: {
        width: 56,
        height: 24,
        // backgroundColor: "#EC6138",
        borderRadius: 12,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center"
    },
    activityMoneyText: {
        color: "#EC6138",
        fontSize: 18,
    },
    activityTagWarp: {
        position: "absolute",
        width: 68,
        height: 17,
        flexDirection: "row",
        // justifyContent: "center",
        alignItems: "center",
        // backgroundColor: "red",
    },
    tagText: {
        fontSize: 9,
        textAlign: "center",
        color: "#fff",
        marginLeft: 4,
        fontWeight: "bold"
    },
    refreshHeader: {
        alignItems: 'center',
        padding: 20,
    },
    refreshIcon: {
        width: 12,
        height: 12,
        marginBottom: 10,
    },
    refreshText: {
        fontSize: 12,
        color: '#333',
    },
    headersIcon: {
        // backgroundColor: "red",
    },
});
